package com.zetatech.bdp.core.task;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.zetatech.bdp.core.utils.BeanUtils;
import com.zetatech.bdp.entity.ColumnDef;
import com.zetatech.bdp.entity.Field;
import com.zetatech.bdp.entity.FtpDFile;
import com.zetatech.bdp.entity.Rule;
import com.zetatech.bdp.parser.parser.impl.DeviceLogFileParser;
import com.zetatech.bdp.rule.RuleParser;
import com.zetatech.bdp.writer.WriterHandler;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author cheng.cao@zetatech.com.cn
 */
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class ParseTask implements Callable<List<Map<String, String>>> {
    private Pattern pattern;
    private FtpDFile ftpDFile;

    @Override
    public List<Map<String, String>> call() throws Exception {
        try {
            String remote = ftpDFile.getRemote();
            if (!ftpDFile.isSuccess()) {
                log.error("该日志文件为下载失败的日志文件: {}，跳过", remote);
                return Lists.newArrayList();
            }
            Matcher m = pattern.matcher(remote);
            List<String> keys = new ArrayList<>();
            while (m.find()) {
                if(keys.size()<2){
                    keys.add(m.group().replaceAll("\\d+", ""));
                }
            }
            String key = Joiner.on("_").join(keys);
            Rule rule = RuleParser.getFields(key);
            if (rule == null) {
                log.error("文件{}未找到对应的解析规则，忽略!", remote);
                return Lists.newArrayList();
            }
            List<Field> fields = rule.getFields();
            List<ColumnDef> columnDefs = fields.stream().map(f -> new ColumnDef(f.getColumn(),f.getType())).collect(Collectors.toList());
            DeviceLogFileParser parser = new DeviceLogFileParser(BeanUtils.getBean(rule.getClazz()));
            List<Map<String, String>> datas = parser.parse(new File(ftpDFile.getLocal()), fields);
            log.info(remote + " ==> " + datas.size());
//            WriterHandler handler = BeanUtils.getBean(rule.getWriter().getClass().getAnnotation(com.zetatech.bdp.annotation.WriterHandler.class).value());
//            handler.write(rule.getWriter(), columnDefs,datas);
            return datas;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Lists.newArrayList();

    }

}




